package cn.yav.web.responsive;

import java.util.*;

/**
 * @author zn
 * @description 组装数据集
 * @date 2019/11/13 18:10
 * @Copyright: 2019 www.yavyun.net Inc. All rights reserved.
 * 注意：本内容仅限于浙江智飨科技内部传阅，禁止外泄以及用于其他的商业目
 */
public class WorksheetPageFindMap {
    private Map<Long,Map<String,Object>> resultMap = new HashMap<>();
    //行ID
    private Long rowId;
    //行Map
    private Map<String,Object> rowMap;
    //子表单List
    private List<Map<String,String>> slaveList;
    //子表单Map
    private Map<String,String> slaveMap;

    public  List<Map<String, Object>> dealMap(List<Map<String,String>> list,String detailKey){
        for (Map<String, String> oldMap : list) {
            rowMap = new HashMap<>();
            slaveMap = new HashMap<>();
            Set<String> keySet = oldMap.keySet();
            for (String key : keySet) {
                String value = String.valueOf(oldMap.get(key));
                if (key.equals("id")){
                    rowId = Long.valueOf(value);
                    init(detailKey);
                    append(key,rowId);
                }else {
                    if (key.contains(detailKey+"_")){
                        dealSlaveMap(key.split(detailKey+"_")[1],value);
                    }else {
                        /*if (key.contains("date")){
                            value = value.split("\\.")[0];
                        }*/
                        append(key,value);
                    }
                }
            }
            dealSlaveList(detailKey);
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : resultMap.values()) {
            resultList.add(stringObjectMap);
        }
        return resultList;
    }
    private void init(String detailKey){
        Map<String, Object> oldRowMap = resultMap.get(rowId);
        if (oldRowMap != null){
            List<Map<String,String>> oldSlaveList = (List) oldRowMap.get(detailKey);
            if (oldSlaveList != null){

                if (rowMap.get(detailKey) == null){
                    slaveList = new ArrayList<>();
                }
                slaveList.addAll(oldSlaveList);
                append(detailKey,slaveList);
            }
        }
        resultMap.put(rowId,rowMap);
    }
    private void append(String key,Object value){
        rowMap.put(key,value);
    }
    private void dealSlaveMap(String key,String value){
        slaveMap.put(key,value);
    }
    private void dealSlaveList(String detailKey){
        if (slaveMap.size() > 0 ){
            slaveList =   (List) rowMap.get(detailKey);
            if (slaveList == null){
                slaveList = new ArrayList<>();
                append(detailKey,slaveList);
            }
            slaveList.add(slaveMap);
        }
    }
}
